<template>
  <div class="page-container">
    <!-- 页面头部 -->
    <PageHeader title="出纳日记账">
      <!-- 搜索和筛选区域 -->
      <template #search-filters>
        <!-- 银行账户选择 -->
        <div class="bank-account-select">
          <span class="label">银行账户：</span>
          <el-tooltip content="支持输入关键词搜索银行账户" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <el-select
            v-model="searchParams.yhzhId"
            placeholder="选择银行账户"
            clearable
            filterable
            remote
            :remote-method="searchBankAccounts"
            :loading="bankAccountLoading"
            style="width: 200px;"
            @change="handleSearch"
          >
            <el-option
              v-for="account in bankAccounts"
              :key="account.id"
              :label="account.yhzhmc"
              :value="account.id"
            />
          </el-select>
        </div>

        <!-- 日期范围选择 -->
        <div class="date-range-select">
          <span class="label">日期范围：</span>
          <el-tooltip content="点击快速选择按钮可快速设置日期范围" placement="top">
            <el-icon class="help-icon"><QuestionFilled /></el-icon>
          </el-tooltip>
          <div class="date-picker-container">
            <el-date-picker
              v-model="searchParams.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 320px;"
              size="default"
              @change="handleSearch"
            />
            <el-dropdown @command="setDateRange" trigger="click">
              <el-button size="default" type="primary">
                <el-icon><Calendar /></el-icon>
                快速选择
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="currentMonth">
                    <el-icon><Calendar /></el-icon>
                    本月
                  </el-dropdown-item>
                  <el-dropdown-item command="lastMonth">
                    <el-icon><Calendar /></el-icon>
                    上月
                  </el-dropdown-item>
                  <el-dropdown-item command="currentYear">
                    <el-icon><Calendar /></el-icon>
                    本年
                  </el-dropdown-item>
                  <el-dropdown-item command="lastYear">
                    <el-icon><Calendar /></el-icon>
                    上年
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </template>

      <!-- 主要操作按钮 -->
      <template #main-actions>
        <el-button @click="showBalanceDialog" type="primary">
          <el-icon><Wallet /></el-icon>
          账户余额
        </el-button>
        <el-button @click="showInternalTransferDialog" type="warning">
          <el-icon><Switch /></el-icon>
          内部调拨
        </el-button>
        <el-button @click="handleAdd" type="success">
          <el-icon><Plus /></el-icon>
          新建流水
        </el-button>
      </template>

      <!-- 更多操作下拉菜单 -->
      <template #more-actions>
        <el-dropdown @command="handleMoreAction">
          <el-button type="info">
            <el-icon><More /></el-icon>
            更多
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="incomeExpense" icon="Folder">收支项目</el-dropdown-item>
              <el-dropdown-item command="contract" icon="Document">合同筛选</el-dropdown-item>
              <el-dropdown-item command="businessDesc" icon="Document">业务描述</el-dropdown-item>
              <el-dropdown-item command="operator" icon="User">经办人</el-dropdown-item>
              <el-dropdown-item command="counterparty" icon="OfficeBuilding">对方单位</el-dropdown-item>
              <el-dropdown-item command="textFilter" icon="Search">文本过滤</el-dropdown-item>
              <el-dropdown-item command="columnConfig" icon="Setting">列配置</el-dropdown-item>
              <el-dropdown-item command="export" icon="Download">导出Excel</el-dropdown-item>
              <el-dropdown-item command="reset" icon="Refresh" divided>重置</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </template>
    </PageHeader>



            <!-- 数据表格 -->
    <div class="table-container">
      <!-- 使用 BaseTable 组件 -->
      <BaseTable
        table-name="cashFlowTable"
        :columns="tableColumns"
        :data="state.pageData"
        :loading="state.loading"
        :sort="sort"
        @sort-change="handleSortChange"
      >
        <!-- 收入金额列自定义内容 -->
        <template #srje="{ row }">
          <span v-if="row.srje" class="income-amount">
            {{ formatCurrency(row.srje) }}
          </span>
        </template>
        
        <!-- 支出金额列自定义内容 -->
        <template #zcje="{ row }">
          <span v-if="row.zcje" class="expense-amount">
            {{ formatCurrency(row.zcje) }}
          </span>
        </template>
        
        <!-- 附件列自定义内容 -->
        <template #attachmentIds="{ row }">
          <el-button 
            v-if="row.fjIds"
            type="text" 
            size="small"
            @click="showAttachments(row)"
          >
            查看附件
          </el-button>
        </template>
        
        <!-- 操作列自定义内容 -->
        <template #actions="{ row }">
          <el-button type="text" size="small" @click="handleEdit(row)">
            编辑
          </el-button>
          <el-button type="text" size="small" @click="handleDelete(row)" class="danger-text">
            删除
          </el-button>
        </template>
      </BaseTable>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="state.currentPage"
          v-model:page-size="state.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="state.totalItems"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 收支项目选择对话框 -->
    <el-dialog v-model="showIncomeExpenseDialog" title="选择收支项目" width="500px" class="income-expense-dialog">
      <div class="income-expense-dialog">
        <el-tree-select
          v-model="searchParams.szxmId"
          :data="incomeExpenseTree"
          placeholder="选择收支项目"
          clearable
          check-strictly
          default-expand-all
          style="width: 100%;"
          :props="{
            children: 'children',
            label: 'szxmmc',
            value: 'id'
          }"
          @change="handleTreeSelectChange"
        />
      </div>
      <template #footer>
        <el-button @click="showIncomeExpenseDialog = false">取消</el-button>
        <el-button type="primary" @click="showIncomeExpenseDialog = false">确定</el-button>
      </template>
    </el-dialog>

    <!-- 银行账户选择对话框 -->
    <el-dialog v-model="showBankAccountDialog" title="选择银行账户" width="500px" class="bank-account-dialog">
      <div class="bank-account-dialog">
        <p class="dialog-tip">请选择一个银行账户作为默认过滤条件：</p>
        <el-select
          v-model="selectedBankAccountId"
          placeholder="选择银行账户"
          clearable
          filterable
          style="width: 100%;"
        >
          <el-option
            v-for="account in bankAccounts"
            :key="account.id"
            :label="account.yhzhmc"
            :value="account.id"
          />
        </el-select>
        <div class="filter-tips">
          <p>选择后将作为页面的默认银行账户过滤条件</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="cancelBankAccountSelection">取消</el-button>
        <el-button type="primary" @click="confirmBankAccountSelection">确认</el-button>
      </template>
    </el-dialog>

    <!-- 合同筛选对话框 -->
    <el-dialog v-model="showContractDialog" title="合同筛选" width="500px" class="contract-dialog">
      <div class="contract-dialog">
        <el-select
          v-model="searchParams.htId"
          placeholder="选择合同"
          clearable
          filterable
          remote
          :remote-method="searchContracts"
          :loading="contractLoading"
          style="width: 100%;"
        >
          <el-option
            v-for="contract in contracts"
            :key="contract.id"
            :label="`${contract.contractNumber || contract.htbh || ''} - ${contract.contractName || contract.htmc || ''}`"
            :value="contract.id"
          />
        </el-select>
        <div class="filter-tips">
          <p>支持输入合同编号或合同名称进行搜索</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="showContractDialog = false">取消</el-button>
        <el-button type="primary" @click="applyContractFilter">应用筛选</el-button>
      </template>
    </el-dialog>

    <!-- 文本过滤对话框 -->
    <el-dialog v-model="showTextFilterDialog" :title="getTextFilterTitle()" width="500px" class="text-filter-dialog">
      <div class="text-filter-dialog">
        <el-input
          v-model="textFilterValue"
          :placeholder="getTextFilterPlaceholder()"
          clearable
          style="width: 100%;"
        />
        <div class="filter-tips">
          <p>{{ getTextFilterTips() }}</p>
        </div>
      </div>
      <template #footer>
        <el-button @click="showTextFilterDialog = false">取消</el-button>
        <el-button type="primary" @click="applyTextFilter">应用过滤</el-button>
      </template>
    </el-dialog>

    <!-- 列配置对话框 - 已删除 -->

    <!-- 余额查询对话框 -->
    <el-dialog v-model="balanceDialogVisible" title="银行账户余额查询" width="1200px" class="balance-query-dialog">
      <div class="balance-query">
        <el-form :model="balanceQueryForm" label-width="100px">
          <el-form-item label="查询日期">
            <el-date-picker
              v-model="balanceQueryForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
            />
          </el-form-item>
        </el-form>
        
        <div class="balance-results" v-if="balanceData.length > 0">
          <h4>银行账户余额</h4>
          <el-table :data="balanceData" border style="width: 100%" class="balance-table">
            <el-table-column prop="yhzhmc" label="账户名称" min-width="120" />
            <el-table-column prop="yhmc" label="银行名称" min-width="100" />
            <el-table-column prop="yhzhh" label="银行账号" min-width="150" />
            <el-table-column prop="zhlx" label="账户类型" min-width="100" />
            <el-table-column prop="qcjy" label="期初结余" align="right" min-width="120">
              <template #default="scope">
                <span class="amount-text">¥{{ formatNumber(scope.row.qcjy) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="bqsr" label="本期收入" align="right" min-width="120">
              <template #default="scope">
                <span class="income-amount">¥{{ formatNumber(scope.row.bqsr) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="bqzc" label="本期支出" align="right" min-width="120">
              <template #default="scope">
                <span class="expense-amount">¥{{ formatNumber(scope.row.bqzc) }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="qmye" label="期末余额" align="right" min-width="120">
              <template #default="scope">
                <span class="amount-text" :class="scope.row.qmye >= 0 ? 'income-amount' : 'expense-amount'">
                  ¥{{ formatNumber(scope.row.qmye) }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <template #footer>
        <el-button @click="balanceDialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="queryBalance" :loading="balanceLoading">查询余额</el-button>
      </template>
    </el-dialog>

    <!-- 内部调拨对话框 -->
    <el-dialog v-model="internalTransferDialogVisible" title="内部调拨" width="600px" class="internal-transfer-dialog">
      <el-form :model="internalTransferForm" :rules="internalTransferRules" ref="internalTransferFormRef" label-width="120px">
        <el-form-item label="调拨日期" prop="transferDate">
          <el-date-picker
            v-model="internalTransferForm.transferDate"
            type="date"
            placeholder="选择调拨日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="业务描述" prop="businessDesc">
          <el-input
            v-model="internalTransferForm.businessDesc"
            placeholder="请输入业务描述"
            type="textarea"
            :rows="3"
          />
        </el-form-item>
        <el-form-item label="调出银行" prop="fromAccountId">
          <el-select
            v-model="internalTransferForm.fromAccountId"
            placeholder="选择调出银行账户"
            style="width: 100%"
          >
            <el-option
              v-for="account in bankAccounts"
              :key="account.id"
              :label="account.yhzhmc"
              :value="account.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调入银行" prop="toAccountId">
          <el-select
            v-model="internalTransferForm.toAccountId"
            placeholder="选择调入银行账户"
            style="width: 100%"
          >
            <el-option
              v-for="account in bankAccounts"
              :key="account.id"
              :label="account.yhzhmc"
              :value="account.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="调拨金额" prop="transferAmount">
          <el-input-number
            v-model="internalTransferForm.transferAmount"
            placeholder="请输入调拨金额"
            :precision="2"
            :min="0.01"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="支出项目" prop="expenseItemId">
          <el-tree-select
            v-model="internalTransferForm.expenseItemId"
            :data="incomeExpenseTree"
            :props="incomeExpenseTreeProps"
            placeholder="请选择支出项目"
            style="width: 100%"
            clearable
            check-strictly
            :render-after-expand="false"
            @change="(value) => handleInternalTransferTreeSelectChange(value, 'expense')"
          />
        </el-form-item>
        <el-form-item label="收入项目" prop="incomeItemId">
          <el-tree-select
            v-model="internalTransferForm.incomeItemId"
            :data="incomeExpenseTree"
            :props="incomeExpenseTreeProps"
            placeholder="请选择收入项目"
            style="width: 100%"
            clearable
            check-strictly
            :render-after-expand="false"
            @change="(value) => handleInternalTransferTreeSelectChange(value, 'income')"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="internalTransferDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitInternalTransfer" :loading="transferLoading">
          确认调拨
        </el-button>
      </template>
    </el-dialog>

    <!-- 列配置对话框 -->
    <el-dialog v-model="columnConfigVisible" title="列配置" width="600px" class="column-config-dialog">
      <div class="column-config">
        <div class="column-list">
          <div v-for="column in tableColumns" :key="column.prop" class="column-item">
            <div class="column-info">
              <el-checkbox 
                v-model="column.visible" 
                :label="column.label"
                @change="handleColumnVisibilityChange"
              />
            </div>
            <div class="column-width" v-if="column.visible">
              <span class="width-label">宽度:</span>
              <el-input-number
                v-model="column.width"
                :min="80"
                :max="500"
                :step="10"
                size="small"
                style="width: 100px;"
                @change="handleColumnWidthChange"
              />
              <span class="unit">px</span>
            </div>
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="resetColumnConfig">重置</el-button>
          <el-button type="primary" @click="saveColumnConfig">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 新建/编辑流水对话框 -->
    <el-dialog 
      v-model="cashFlowDialogVisible" 
      :title="dialogTitle" 
      width="800px"
      class="cash-flow-dialog"
    >
      <el-form 
        :model="cashFlowForm" 
        :rules="cashFlowRules" 
        ref="cashFlowFormRef" 
        label-width="120px"
        class="cash-flow-form"
      >
        <!-- 基本信息 -->
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <div class="form-row">
                      <el-form-item label="收支日期" prop="szrq">
            <el-date-picker
              v-model="cashFlowForm.szrq"
              type="date"
              placeholder="选择收支日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              @change="validateSzrqRealtime"
            />
            <div v-if="cashFlowForm.yhzhId && cashFlowForm.szrq" class="validation-tip">
              <el-icon v-if="validationStatus.isValid" color="#67c23a"><CircleCheck /></el-icon>
              <el-icon v-else color="#f56c6c"><CircleClose /></el-icon>
              <span v-if="!validationStatus.isValid" :class="{ 'invalid': !validationStatus.isValid }">
                {{ validationStatus.message }}
              </span>
            </div>
          </el-form-item>
            
            <el-form-item label="业务日期" prop="ywrq">
              <el-date-picker
                v-model="cashFlowForm.ywrq"
                type="date"
                placeholder="选择业务日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="收支项目" prop="szxmId">
              <el-tree-select
                v-model="cashFlowForm.szxmId"
                :data="incomeExpenseTree"
                placeholder="选择收支项目"
                clearable
                check-strictly
                default-expand-all
                style="width: 100%"
                :props="{
                  children: 'children',
                  label: 'szxmmc',
                  value: 'id'
                }"
                @change="handleTreeSelectChange"
              />
            </el-form-item>
            
                      <el-form-item label="银行账户" prop="yhzhId">
            <el-select
              v-model="cashFlowForm.yhzhId"
              placeholder="选择银行账户"
              clearable
              filterable
              style="width: 100%"
              @change="validateSzrqRealtime"
            >
              <el-option
                v-for="account in bankAccounts"
                :key="account.id"
                :label="account.yhzhmc"
                :value="account.id"
              />
            </el-select>
          </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="收入金额" prop="srje">
              <el-input-number
                v-model="cashFlowForm.srje"
                placeholder="请输入收入金额"
                :precision="2"
                :min="0"
                style="width: 100%"
                @blur="validateAmounts"
                @change="validateAmounts"
              />
            </el-form-item>
            
            <el-form-item label="支出金额" prop="zcje">
              <el-input-number
                v-model="cashFlowForm.zcje"
                placeholder="请输入支出金额"
                :precision="2"
                :min="0"
                style="width: 100%"
                @blur="validateAmounts"
                @change="validateAmounts"
              />
            </el-form-item>
          </div>
          
          <!-- 金额验证提示 -->
          <div v-if="cashFlowForm.srje !== null || cashFlowForm.zcje !== null" class="amount-validation-tip">
            <el-icon v-if="amountValidationStatus.isValid" color="#67c23a"><CircleCheck /></el-icon>
            <el-icon v-else color="#f56c6c"><CircleClose /></el-icon>
            <span :class="{ 'valid': amountValidationStatus.isValid, 'invalid': !amountValidationStatus.isValid }">
              {{ amountValidationStatus.message }}
            </span>
          </div>

          <div class="form-row single">
            <el-form-item label="业务描述" prop="ywms">
              <el-input
                v-model="cashFlowForm.ywms"
                type="textarea"
                :rows="3"
                placeholder="请输入业务描述"
              />
            </el-form-item>
          </div>
        </div>

        <!-- 辅助信息 -->
        <div class="form-section">
          <div class="section-title">辅助信息</div>
          <div class="form-row">
            <el-form-item label="合同" prop="htId">
              <el-select
                v-model="cashFlowForm.htId"
                placeholder="选择合同"
                clearable
                filterable
                remote
                :remote-method="searchContracts"
                :loading="contractLoading"
                style="width: 100%"
              >
                          <el-option
            v-for="contract in contracts"
            :key="contract.id"
            :label="`${contract.contractNumber || contract.htbh || ''} - ${contract.contractName || contract.htmc || ''}`"
            :value="contract.id"
          />
              </el-select>
            </el-form-item>
            
            <el-form-item label="经办人" prop="jbr">
              <el-input
                v-model="cashFlowForm.jbr"
                placeholder="请输入经办人"
              />
            </el-form-item>
          </div>

          <div class="form-row single">
            <el-form-item label="对方单位" prop="dfdwmc">
              <el-input
                v-model="cashFlowForm.dfdwmc"
                placeholder="请输入对方单位名称"
              />
            </el-form-item>
          </div>
        </div>

        <!-- 分摊费用 -->
        <div class="form-section">
          <div class="section-title">分摊费用</div>
          <div class="form-row">
            <el-form-item label="分配方法" prop="fpff">
              <el-input
                v-model="cashFlowForm.fpff"
                placeholder="请输入分配方法"
              />
            </el-form-item>
            
            <el-form-item label="甲方金额" prop="jfje">
              <el-input-number
                v-model="cashFlowForm.jfje"
                placeholder="请输入甲方金额"
                :precision="2"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </div>

          <div class="form-row">
            <el-form-item label="乙方金额" prop="yfje">
              <el-input-number
                v-model="cashFlowForm.yfje"
                placeholder="请输入乙方金额"
                :precision="2"
                :min="0"
                style="width: 100%"
              />
            </el-form-item>
          </div>
        </div>

        <!-- 备注信息 -->
        <div class="form-section">
          <div class="section-title">备注信息</div>
          <div class="form-row single">
            <el-form-item label="备注" prop="bz">
              <el-input
                v-model="cashFlowForm.bz"
                type="textarea"
                :rows="3"
                placeholder="请输入备注"
              />
            </el-form-item>
          </div>
        </div>

                        <div class="form-row single">
                  <el-form-item label="附件上传">
                    <el-upload
                      ref="uploadRef"
                      :action="uploadUrl"
                      :headers="uploadHeaders"
                      :file-list="fileList"
                      :on-preview="handleFilePreview"
                      :on-remove="handleFileRemove"
                      :on-success="handleFileSuccess"
                      :on-error="handleFileError"
                      :before-upload="beforeFileUpload"
                      multiple
                      :limit="10"
                      :file-size="10"
                      accept=".jpg,.jpeg,.png,.gif,.pdf,.doc,.docx,.xls,.xlsx"
                      list-type="text"
                      class="upload-area"
                    >
                      <el-icon><Plus /></el-icon>
                      <div class="upload-text">点击上传</div>
                    </el-upload>
                  </el-form-item>
                </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cashFlowDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitCashFlow" :loading="submitLoading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 附件查看对话框 -->
    <el-dialog 
      v-model="attachmentDialogVisible" 
      title="出纳日记账附件" 
      width="800px"
      class="attachment-dialog"
    >
      <div v-if="selectedCashFlow" class="attachment-content">
        <div class="cashflow-info">
          <h4>流水记录</h4>
          <p>流水编号：{{ selectedCashFlow.id }}</p>
          <p>交易日期：{{ selectedCashFlow.jyrq }}</p>
          <p>交易金额：¥{{ formatNumber(selectedCashFlow.jyje) }}</p>
        </div>
        
        <div class="attachment-list" v-if="attachmentList.length > 0">
          <div class="attachment-item" v-for="attachment in attachmentList" :key="attachment.id">
            <div class="attachment-info">
              <div class="attachment-name">{{ attachment.originalFilename }}</div>
              <div class="attachment-meta">
                <span class="file-size">{{ formatFileSize(attachment.fileSize) }}</span>
                <span class="file-type">{{ attachment.fileType }}</span>
                <span class="upload-time">{{ formatAttachmentDate(attachment.createTime) }}</span>
                <span v-if="attachment.subDirectory" class="sub-directory">目录: {{ attachment.subDirectory }}</span>
              </div>
            </div>
            <div class="attachment-actions">
              <el-button type="primary" size="small" @click="previewAttachment(attachment)">
                <el-icon><Document /></el-icon>
                预览
              </el-button>
              <el-button type="success" size="small" @click="downloadAttachment(attachment)">
                <el-icon><Download /></el-icon>
                下载
              </el-button>
            </div>
          </div>
        </div>
        
        <div v-else class="no-attachments">
          <el-empty description="暂无附件" />
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import { useUserStore } from '@/stores/userStore'
import { 
  Wallet, 
  Switch, 
  Plus, 
  More, 
  Calendar, 
  QuestionFilled,
  Search,
  Refresh,
  Setting,
  Download,
  Upload,
  ArrowDown,
  Document,
  DocumentCopy,
  OfficeBuilding,
  CircleCheck,
  CircleClose
} from '@element-plus/icons-vue'
import BaseTable from '@/components/tools/BaseTable.vue'
import useTable from '@/composables/useTable.js'
import cashFlowApi from '@/api/cashFlowApi.js'
import bankAccountApi from '@/api/bankaccountApi'
import incomeExpenseApi from '@/api/incomeExpenseApi'
import contractApi from '@/api/contractApi'
import attachmentApi from '@/api/attachmentApi'
import PageHeader from '@/components/layout/PageHeader.vue'
    // 数据获取函数
    async function fetchCashFlowData(params) {
      try {
        // 处理日期范围参数
        const apiParams = { ...params }
        
        // 将dateRange数组转换为startDate和endDate
        if (params.dateRange && Array.isArray(params.dateRange) && params.dateRange.length === 2) {
          apiParams.startDate = params.dateRange[0]
          apiParams.endDate = params.dateRange[1]
          // 删除dateRange参数，避免传递给API
          delete apiParams.dateRange
        }
        
        console.log('fetchCashFlowData 处理后的参数:', apiParams)
        const response = await cashFlowApi.getList(apiParams)
        
        // 标准化响应数据，确保返回正确的格式
        const responseData = response.data || response
        
        // 处理不同的响应格式
        let content = []
        let total = 0
        
        if (responseData && Array.isArray(responseData.content)) {
          content = responseData.content
          // 如果total为0但content有数据，使用content的长度作为total
          total = responseData.total || content.length
        } else if (responseData && Array.isArray(responseData.records)) {
          content = responseData.records
          total = responseData.total || content.length
        } else if (Array.isArray(responseData)) {
          content = responseData
          total = responseData.length
        } else if (responseData && Array.isArray(responseData.data)) {
          content = responseData.data
          total = responseData.total || content.length
        } else {
          content = []
          total = 0
        }
        
        return { content, total }
      } catch (error) {
        console.error('获取数据失败:', error)
        throw error
      }
    }

    // 使用通用表格组合式API
    const { state, loadData, handleSortChange, updateSearchParams, resetSearchParams, setSearchKeyword } = useTable(fetchCashFlowData)

    // 响应式数据
    const bankAccounts = ref([])
    const bankAccountLoading = ref(false)
    const incomeExpenseTree = ref([])
    const contracts = ref([])
    const contractLoading = ref(false)
    const balanceDialogVisible = ref(false)
    const balanceLoading = ref(false)
    const internalTransferDialogVisible = ref(false)
    const attachmentDialogVisible = ref(false)
    const transferLoading = ref(false)
    
    // 内部调拨收支项目ID
    const internalTransferExpenseId = ref(null)
    const internalTransferIncomeId = ref(null)
    
    // 收支项目树配置
    const incomeExpenseTreeProps = {
      children: 'children',
      label: 'szxmmc',
      value: 'id'
    }
    
    // 搜索参数 - 修改为与useTable兼容的格式
    const searchParams = reactive({
      yhzhId: null,
      szxmId: null,
      htId: null,
      dateRange: null
    })
    
    // 排序
    const sort = ref({})
    
    // 表格列配置 - 包含所有字段，默认显示主要字段
    const tableColumns = ref([
      // 主要字段 - 默认显示
      { prop: 'szrq', label: '收支日期', width: 140, visible: true },
      { prop: 'ywrq', label: '业务日期', width: 140, visible: false },
      { prop: 'szxmId', label: '收支项目ID', width: 100, visible: false },
      { prop: 'szxmmc', label: '收支项目', width: 150, visible: true },
      { prop: 'ywms', label: '业务描述', minWidth: 300, visible: true },
      { prop: 'srje', label: '收入金额', width: 140, align: 'right', slot: 'srje', visible: true },
      { prop: 'zcje', label: '支出金额', width: 140, align: 'right', slot: 'zcje', visible: true },
      { prop: 'yhzhId', label: '银行账户ID', width: 100, visible: false },
      { prop: 'yhzhmc', label: '银行账户', width: 150, visible: true },
      { prop: 'htId', label: '合同ID', width: 100, visible: false },
      { prop: 'contractName', label: '合同名称', width: 250, visible: true },
      { prop: 'fpff', label: '分配方法', width: 100, visible: false },
      { prop: 'jfje', label: '甲方金额', width: 120, align: 'right', visible: false },
      { prop: 'yfje', label: '乙方金额', width: 120, align: 'right', visible: false },
      { prop: 'dfdwmc', label: '对方单位名称', width: 150, visible: false },
      { prop: 'jbr', label: '经办人', width: 100, visible: false },
      { prop: 'bz', label: '备注', width: 200, visible: false },
      { prop: 'fjIds', label: '附件', width: 100, align: 'center', slot: 'attachmentIds', visible: true },
      { prop: 'cjrId', label: '创建人ID', width: 100, visible: false },
      { prop: 'cjrName', label: '创建人', width: 100, visible: false },
      { prop: 'cjrq', label: '创建日期', width: 150, visible: false },
      { prop: 'xgrId', label: '修改人ID', width: 100, visible: false },
      { prop: 'xgrName', label: '修改人', width: 100, visible: false },
      { prop: 'xgrq', label: '修改日期', width: 150, visible: false },
      { prop: 'zt', label: '状态', width: 80, visible: false },
      { prop: 'id', label: 'ID', width: 80, visible: false },
      { prop: 'actions', label: '操作', width: 180, slot: 'actions', fixed: 'right', visible: true }
    ])
    

    
    // 余额查询表单
    const balanceQueryForm = reactive({
      dateRange: null
    })
    const balanceData = ref([])
    
    // 内部调拨表单
    const internalTransferForm = reactive({
      transferDate: null,
      businessDesc: '',
      fromAccountId: null,
      toAccountId: null,
      transferAmount: null,
      expenseItemId: null, // 支出项目ID
      incomeItemId: null   // 收入项目ID
    })
    
    // 内部调拨表单验证规则
    const internalTransferRules = {
      transferDate: [{ required: true, message: '请选择调拨日期', trigger: 'change' }],
      businessDesc: [{ required: true, message: '请输入业务描述', trigger: 'blur' }],
      fromAccountId: [{ required: true, message: '请选择调出银行账户', trigger: 'change' }],
      toAccountId: [
        { required: true, message: '请选择调入银行账户', trigger: 'change' },
        { 
          validator: (rule, value, callback) => {
            if (value && internalTransferForm.fromAccountId && value === internalTransferForm.fromAccountId) {
              callback(new Error('调出银行账户和调入银行账户不能相同'))
            } else {
              callback()
            }
          }, 
          trigger: 'change' 
        }
      ],
      transferAmount: [
        { required: true, message: '请输入调拨金额', trigger: 'blur' },
        { type: 'number', min: 0.01, message: '调拨金额必须大于0', trigger: 'blur' }
      ],
      expenseItemId: [{ required: true, message: '请选择支出项目', trigger: 'change' }],
      incomeItemId: [{ required: true, message: '请选择收入项目', trigger: 'change' }]
    }
    
    // 附件相关
    const attachmentList = ref([])
    const selectedCashFlow = ref(null)
    const internalTransferFormRef = ref(null)
    const showAdvancedFilter = ref(false)
    const showIncomeExpenseDialog = ref(false)
    const showTextFilterDialog = ref(false)
    const textFilterValue = ref('')
    const textFilterType = ref('general') // 文本过滤类型：general, businessDesc, operator, counterparty
    const columnConfigVisible = ref(false)
    const showContractDialog = ref(false)
    const showBankAccountDialog = ref(false)
    const selectedBankAccountId = ref(null)
    
    // 新建/编辑流水对话框相关
    const cashFlowDialogVisible = ref(false)
    const dialogTitle = ref('新建流水')
    const submitLoading = ref(false)
    const cashFlowFormRef = ref()
    
    // 流水表单数据
    const cashFlowForm = reactive({
      id: null,
      szrq: '',
      ywrq: '',
      szxmId: null,
      ywms: '',
      srje: null,
      zcje: null,
      yhzhId: null,
      htId: null,
      fpff: '',
      jfje: null,
      yfje: null,
      dfdwmc: '',
      jbr: '',
      bz: '',
      fjIds: ''
    })
    
    // 流水表单验证规则
    const cashFlowRules = {
      szrq: [
        { required: true, message: '请选择收支日期', trigger: 'change' },
        { 
          validator: async (rule, value, callback) => {
            if (value && cashFlowForm.yhzhId) {
              try {
                const result = await validateSzrq(cashFlowForm.yhzhId, value)
                if (!result.isValid) {
                  callback(new Error(result.message || '收支日期不能早于银行账户启用日期'))
                } else {
                  callback()
                }
              } catch (error) {
                console.error('验证失败:', error)
                callback() // 验证失败时默认通过
              }
            } else {
              callback()
            }
          }, 
          trigger: 'change' 
        }
      ],
      ywrq: [{ required: true, message: '请选择业务日期', trigger: 'change' }],
      szxmId: [{ required: true, message: '请选择收支项目', trigger: 'change' }],
      yhzhId: [{ required: true, message: '请选择银行账户', trigger: 'change' }],
      ywms: [{ required: true, message: '请输入业务描述', trigger: 'blur' }],
      srje: [
        { 
          validator: (rule, value, callback) => {
            const srje = value || 0
            const zcje = cashFlowForm.zcje || 0
            
            if (srje === 0 && zcje === 0) {
              callback(new Error('收入金额和支出金额不能同时为0'))
            } else if (srje > 0 && zcje > 0) {
              callback(new Error('收入金额和支出金额不能同时大于0'))
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ],
      zcje: [
        { 
          validator: (rule, value, callback) => {
            const srje = cashFlowForm.srje || 0
            const zcje = value || 0
            
            if (srje === 0 && zcje === 0) {
              callback(new Error('收入金额和支出金额不能同时为0'))
            } else if (srje > 0 && zcje > 0) {
              callback(new Error('收入金额和支出金额不能同时大于0'))
            } else {
              callback()
            }
          }, 
          trigger: 'blur' 
        }
      ]
    }
    
    // 文件上传相关
    const uploadRef = ref()
    const fileList = ref([])
    const uploadUrl = '/api/attachments/upload'
    const uploadHeaders = {
      'Authorization': `Bearer ${localStorage.getItem('token')}`
    }
    
    // 保存原始列配置用于重置
    const originalTableColumns = ref([])
    

    
    // 方法 - 使用 useTable 提供的 loadData
    
    const loadBankAccounts = async () => {
      try {
        const response = await bankAccountApi.getList({ page: 1, size: 1000 })
        const data = response.data || response
        bankAccounts.value = data.content || data.records || data || []
      } catch (error) {
        console.error('加载银行账户失败:', error)
        bankAccounts.value = []
      }
    }
    
    // 搜索银行账户
    const searchBankAccounts = async (query) => {
      if (query !== '') {
        bankAccountLoading.value = true
        try {
          const response = await bankAccountApi.getList({ 
            page: 1, 
            size: 1000,
            keyword: query 
          })
          const data = response.data || response
          const allAccounts = data.content || data.records || data || []
          // 过滤包含查询关键词的账户
          bankAccounts.value = allAccounts.filter(account => 
            account.yhzhmc && account.yhzhmc.toLowerCase().includes(query.toLowerCase())
          )
        } catch (error) {
          console.error('搜索银行账户失败:', error)
          bankAccounts.value = []
        } finally {
          bankAccountLoading.value = false
        }
      } else {
        // 如果查询为空，加载所有账户
        await loadBankAccounts()
      }
    }
    
    const loadIncomeExpenseTree = async () => {
      try {
        const response = await incomeExpenseApi.getList({ page: 1, size: 1000 })
        const data = response.data || response
        const items = data.content || data.records || data || []
        
        // 构建树状结构
        const buildTree = (items) => {
          const itemMap = new Map()
          const rootItems = []
          
          // 首先创建所有项目的映射
          items.forEach(item => {
            itemMap.set(item.id, { ...item, children: [] })
          })
          
          // 构建父子关系
          items.forEach(item => {
            const node = itemMap.get(item.id)
            if (item.parentId === 0 || item.parentId === null) {
              // 根节点
              rootItems.push(node)
            } else {
              // 子节点
              const parent = itemMap.get(item.parentId)
              if (parent) {
                parent.children.push(node)
              }
            }
          })
          
          return rootItems
        }
        
        incomeExpenseTree.value = buildTree(items)
        console.log('收支项目树数据:', incomeExpenseTree.value)
        
        // 设置内部调拨的收支项目ID
        await setInternalTransferIncomeExpenseIds(items)
      } catch (error) {
        console.error('加载收支项目树失败:', error)
        incomeExpenseTree.value = []
      }
    }
    
    // 设置内部调拨的收支项目ID
    const setInternalTransferIncomeExpenseIds = async (items) => {
      try {
        // 查找合适的收支项目用于内部调拨
        const expenseItems = items.filter(item => 
          item.szxmmc && (
            item.szxmmc.includes('调拨') || 
            item.szxmmc.includes('转移') || 
            item.szxmmc.includes('支出') ||
            item.szxmmc.includes('内部')
          )
        )
        
        const incomeItems = items.filter(item => 
          item.szxmmc && (
            item.szxmmc.includes('调拨') || 
            item.szxmmc.includes('转移') || 
            item.szxmmc.includes('收入') ||
            item.szxmmc.includes('内部')
          )
        )
        
        // 设置支出项目ID（优先选择包含"调拨"的项目）
        if (expenseItems.length > 0) {
          const expenseItem = expenseItems.find(item => item.szxmmc.includes('调拨')) || expenseItems[0]
          internalTransferExpenseId.value = expenseItem.id
        } else {
          // 如果没有找到合适的，使用第一个项目
          internalTransferExpenseId.value = items[0]?.id || 1
        }
        
        // 设置收入项目ID（优先选择包含"调拨"的项目）
        if (incomeItems.length > 0) {
          const incomeItem = incomeItems.find(item => item.szxmmc.includes('调拨')) || incomeItems[0]
          internalTransferIncomeId.value = incomeItem.id
        } else {
          // 如果没有找到合适的，使用第一个项目
          internalTransferIncomeId.value = items[0]?.id || 1
        }
        
        console.log('内部调拨收支项目ID设置完成:', {
          expenseId: internalTransferExpenseId.value,
          incomeId: internalTransferIncomeId.value
        })
      } catch (error) {
        console.error('设置内部调拨收支项目ID失败:', error)
        // 设置默认值
        internalTransferExpenseId.value = 1
        internalTransferIncomeId.value = 1
      }
    }
    
    const searchContracts = async (query) => {
      contractLoading.value = true
      try {
        if (query && query.trim() !== '') {
          // 搜索模式：使用通用搜索参数
          const response = await contractApi.getList({ 
            page: 1, 
            size: 1000,
            search: query // 使用通用的search参数
          })
          const data = response.data || response
          const contractData = data.content || data.records || data || []
          
          // 如果后端不支持通用搜索，则在前端进行过滤
          if (contractData.length > 0 && !contractData.some(contract => 
            (contract.contractNumber || contract.htbh || '').toLowerCase().includes(query.toLowerCase()) ||
            (contract.contractName || contract.htmc || '').toLowerCase().includes(query.toLowerCase())
          )) {
            // 后端搜索没有结果，尝试前端过滤
            const allContracts = await loadAllContracts()
            contracts.value = allContracts.filter(contract => 
              (contract.contractNumber || contract.htbh || '').toLowerCase().includes(query.toLowerCase()) ||
              (contract.contractName || contract.htmc || '').toLowerCase().includes(query.toLowerCase())
            )
          } else {
            contracts.value = contractData
          }
          console.log('搜索合同结果:', contracts.value)
        } else {
          // 初始加载：获取所有合同列表
          const response = await contractApi.getList({ page: 1, size: 1000 })
          const data = response.data || response
          const contractData = data.content || data.records || data || []
          contracts.value = contractData
          console.log('初始加载合同列表:', contracts.value)
        }
      } catch (error) {
        console.error('加载合同失败:', error)
        contracts.value = []
      } finally {
        contractLoading.value = false
      }
    }
    
    // 加载所有合同的辅助方法
    const loadAllContracts = async () => {
      try {
        const response = await contractApi.getList({ page: 1, size: 10000 })
        const data = response.data || response
        return data.content || data.records || data || []
      } catch (error) {
        console.error('加载所有合同失败:', error)
        return []
      }
    }
    
    const handleTreeSelectChange = (value) => {
      // 检查选择的是否为叶子节点
      const isLeafNode = (nodeId) => {
        const findNode = (nodes) => {
          for (const node of nodes) {
            if (node.id === nodeId) {
              return !node.children || node.children.length === 0
            }
            if (node.children && node.children.length > 0) {
              const found = findNode(node.children)
              if (found !== null) return found
            }
          }
          return null
        }
        return findNode(incomeExpenseTree.value)
      }
      
      if (value && !isLeafNode(value)) {
        ElMessage.warning('只能选择末级收支项目')
        searchParams.szxmId = null
        return
      }
      
      searchParams.szxmId = value
      // 更新useTable的搜索参数
      updateSearchParams(searchParams)
      // 确保数据重新加载
      loadData()
    }
    
    // 处理内部调拨收支项目选择变化
    const handleInternalTransferTreeSelectChange = (value, type) => {
      // 检查选择的是否为叶子节点
      const isLeafNode = (nodeId) => {
        const findNode = (nodes) => {
          for (const node of nodes) {
            if (node.id === nodeId) {
              return !node.children || node.children.length === 0
            }
            if (node.children && node.children.length > 0) {
              const found = findNode(node.children)
              if (found !== null) return found
            }
          }
          return null
        }
        return findNode(incomeExpenseTree.value)
      }
      
      if (value && !isLeafNode(value)) {
        ElMessage.warning('只能选择末级收支项目')
        if (type === 'expense') {
          internalTransferForm.expenseItemId = null
        } else if (type === 'income') {
          internalTransferForm.incomeItemId = null
        }
        return
      }
    }
    
    const handleSearch = () => {
      // 更新useTable的搜索参数
      updateSearchParams(searchParams)
      // 确保数据重新加载
      loadData()
    }
    
    const handleSizeChange = (size) => {
      state.pageSize = size
      loadData()
    }
    
    const handleCurrentChange = (current) => {
      state.currentPage = current
      loadData()
    }
    
    // 处理表格排序变化 - 使用 useTable 提供的 handleSortChange
    
    // 处理列配置更新 - 已删除
    
    // 设置日期范围
    const setDateRange = (type) => {
      const now = new Date()
      let startDate, endDate
      
      switch (type) {
        case 'currentMonth':
          // 本月：当月第一天到当月最后一天
          startDate = new Date(now.getFullYear(), now.getMonth(), 1)
          endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0)
          break
        case 'lastMonth':
          // 上月：上月第一天到上月最后一天
          startDate = new Date(now.getFullYear(), now.getMonth() - 1, 1)
          endDate = new Date(now.getFullYear(), now.getMonth(), 0)
          break
        case 'currentYear':
          // 本年：当年1月1日到12月31日
          startDate = new Date(now.getFullYear(), 0, 1)
          endDate = new Date(now.getFullYear(), 11, 31)
          break
        case 'lastYear':
          // 上年：去年1月1日到12月31日
          startDate = new Date(now.getFullYear() - 1, 0, 1)
          endDate = new Date(now.getFullYear() - 1, 11, 31)
          break
        default:
          return
      }
      
      searchParams.dateRange = [
        formatDate(startDate),
        formatDate(endDate)
      ]
      // 更新useTable的搜索参数
      updateSearchParams(searchParams)
      // 确保数据重新加载
      loadData()
    }
    
    // 处理更多操作
    const handleMoreAction = (command) => {
      switch (command) {
        case 'export':
          handleExport()
          break
        case 'incomeExpense':
          showIncomeExpenseDialog.value = true
          break
        case 'contract':
          showContractDialog.value = true
          break
        case 'businessDesc':
          showTextFilterDialog.value = true
          textFilterType.value = 'businessDesc'
          break
        case 'operator':
          showTextFilterDialog.value = true
          textFilterType.value = 'operator'
          break
        case 'counterparty':
          showTextFilterDialog.value = true
          textFilterType.value = 'counterparty'
          break
        case 'textFilter':
          showTextFilterDialog.value = true
          textFilterType.value = 'general'
          break
        case 'columnConfig':
          showColumnConfig()
          break
        case 'reset':
          handleReset()
          break
      }
    }
    
    // 应用合同筛选
    const applyContractFilter = () => {
      showContractDialog.value = false
      updateSearchParams(searchParams)
      loadData()
      ElMessage.success('合同筛选已应用')
    }
    
    // 确认银行账户选择
    const confirmBankAccountSelection = () => {
      if (!selectedBankAccountId.value) {
        ElMessage.warning('请选择一个银行账户')
        return
      }
      
      searchParams.yhzhId = selectedBankAccountId.value
      updateSearchParams(searchParams)
      
      // 保存选择的银行账户到localStorage
      localStorage.setItem('cashFlowDefaultBankAccount', selectedBankAccountId.value.toString())
      
      showBankAccountDialog.value = false
      loadData()
      ElMessage.success('银行账户已设置')
    }
    
    // 取消银行账户选择
    const cancelBankAccountSelection = () => {
      showBankAccountDialog.value = false
      // 如果没有选择银行账户，可以选择默认账户或保持为空
      if (!searchParams.yhzhId && bankAccounts.value.length > 0) {
        searchParams.yhzhId = bankAccounts.value[0].id
        updateSearchParams(searchParams)
        loadData()
      }
    }
    
    // 重置筛选条件
    const handleReset = () => {
      searchParams.yhzhId = null
      searchParams.szxmId = null
      searchParams.htId = null
      searchParams.dateRange = null
      textFilterValue.value = ''
      // 重置useTable的搜索参数
      resetSearchParams()
      // 确保数据重新加载
      loadData()
      ElMessage.success('筛选条件已重置')
    }
    
    // 获取文本过滤标题
    const getTextFilterTitle = () => {
      switch (textFilterType.value) {
        case 'businessDesc':
          return '业务描述过滤'
        case 'operator':
          return '经办人过滤'
        case 'counterparty':
          return '对方单位过滤'
        default:
          return '文本过滤'
      }
    }
    
    // 获取文本过滤占位符
    const getTextFilterPlaceholder = () => {
      switch (textFilterType.value) {
        case 'businessDesc':
          return '请输入业务描述关键词'
        case 'operator':
          return '请输入经办人姓名'
        case 'counterparty':
          return '请输入对方单位名称'
        default:
          return '请输入搜索关键词'
      }
    }
    
    // 获取文本过滤提示
    const getTextFilterTips = () => {
      switch (textFilterType.value) {
        case 'businessDesc':
          return '支持搜索业务描述字段'
        case 'operator':
          return '支持搜索经办人字段'
        case 'counterparty':
          return '支持搜索对方单位名称字段'
        default:
          return '支持搜索：业务描述、合同名称、银行账户等字段'
      }
    }
    
    // 应用文本过滤
    const applyTextFilter = () => {
      // TODO: 实现文本过滤逻辑
      showTextFilterDialog.value = false
      ElMessage.success('文本过滤已应用')
    }
    
    // 显示列配置对话框
    const showColumnConfig = () => {
      columnConfigVisible.value = true
    }
    
    // 处理列显示/隐藏变化
    const handleColumnVisibilityChange = () => {
      console.log('列可见性变化 - tableColumns:', tableColumns.value)
      // 强制更新表格
      nextTick(() => {
        // 触发表格重新渲染
      })
    }
    
    // 处理列宽变化
    const handleColumnWidthChange = () => {
      // 强制更新表格
      nextTick(() => {
        // 触发表格重新渲染
      })
    }
    
    // 重置列配置
    const resetColumnConfig = () => {
      // 恢复原始列配置
      tableColumns.value.forEach((column, index) => {
        if (originalTableColumns.value[index]) {
          column.visible = originalTableColumns.value[index].visible
          column.width = originalTableColumns.value[index].width
        }
      })
      ElMessage.success('列配置已重置')
    }
    
    // 保存列配置
    const saveColumnConfig = () => {
      // 保存到localStorage
      localStorage.setItem('cashFlowTableColumns', JSON.stringify(tableColumns.value))
      columnConfigVisible.value = false
      ElMessage.success('列配置已保存')
    }
    
    const showBalanceDialog = () => {
      balanceDialogVisible.value = true
      // 设置默认日期范围为本月
      const now = new Date()
      const firstDay = new Date(now.getFullYear(), now.getMonth(), 1)
      const lastDay = new Date(now.getFullYear(), now.getMonth() + 1, 0)
      
      balanceQueryForm.dateRange = [
        formatDate(firstDay),
        formatDate(lastDay)
      ]
    }
    
    const queryBalance = async () => {
      try {
        balanceLoading.value = true
        const params = {}
        if (balanceQueryForm.dateRange && balanceQueryForm.dateRange.length === 2) {
          params.startDate = balanceQueryForm.dateRange[0]
          params.endDate = balanceQueryForm.dateRange[1]
        }
        
        const response = await cashFlowApi.getAccountStatistics(params)
        console.log('银行账户统计响应:', response)
        
        if (response.data) {
          balanceData.value = response.data
        } else {
          balanceData.value = response
        }
      } catch (error) {
        console.error('查询余额失败:', error)
        ElMessage.error('查询余额失败')
        balanceData.value = []
      } finally {
        balanceLoading.value = false
      }
    }
    
    const resetInternalTransferForm = () => {
      Object.assign(internalTransferForm, {
        transferDate: formatDate(new Date()),
        businessDesc: '',
        fromAccountId: null,
        toAccountId: null,
        transferAmount: null,
        expenseItemId: null,
        incomeItemId: null
      })
    }
    
    const showInternalTransferDialog = () => {
      internalTransferDialogVisible.value = true
      resetInternalTransferForm()
    }
    
    const submitInternalTransfer = async () => {
      if (!internalTransferFormRef.value) return
      
      try {
        await internalTransferFormRef.value.validate()
        transferLoading.value = true
        
        // 获取当前用户信息
        const userStore = useUserStore()
        const currentUser = userStore.user?.username || userStore.user?.name || '系统用户'
        
        // 创建第一条流水记录：支出记录（调出账户）
        const expenseRecord = {
          szrq: internalTransferForm.transferDate,
          ywrq: internalTransferForm.transferDate,
          szxmId: internalTransferForm.expenseItemId, // 使用用户选择的支出项目ID
          ywms: `内部调拨支出 - ${internalTransferForm.businessDesc}`,
          srje: 0,
          zcje: internalTransferForm.transferAmount,
          yhzhId: internalTransferForm.fromAccountId,
          htId: null,
          fpff: '内部调拨',
          jfje: 0,
          yfje: 0,
          dfdwmc: '',
          jbr: currentUser,
          bz: '内部调拨支出'
        }
        
        // 创建第二条流水记录：收入记录（调入账户）
        const incomeRecord = {
          szrq: internalTransferForm.transferDate,
          ywrq: internalTransferForm.transferDate,
          szxmId: internalTransferForm.incomeItemId, // 使用用户选择的收入项目ID
          ywms: `内部调拨收入 - ${internalTransferForm.businessDesc}`,
          srje: internalTransferForm.transferAmount,
          zcje: 0,
          yhzhId: internalTransferForm.toAccountId,
          htId: null,
          fpff: '内部调拨',
          jfje: 0,
          yfje: 0,
          dfdwmc: '',
          jbr: currentUser,
          bz: '内部调拨收入'
        }
        
        // 使用现有的create接口创建两条流水记录
        await cashFlowApi.create(expenseRecord)
        await cashFlowApi.create(incomeRecord)
        
        ElMessage.success('内部调拨成功')
        internalTransferDialogVisible.value = false
        resetInternalTransferForm()
        loadData() // 重新加载数据
      } catch (error) {
        console.error('内部调拨失败:', error)
        ElMessage.error('内部调拨失败: ' + (error.response?.data?.message || error.message || '未知错误'))
      } finally {
        transferLoading.value = false
      }
    }
    
    const handleAdd = () => {
      dialogTitle.value = '新建流水'
      resetCashFlowForm()
      
      // 默认选择当前银行账户
      if (searchParams.yhzhId) {
        cashFlowForm.yhzhId = searchParams.yhzhId
      }
      
      cashFlowDialogVisible.value = true
    }
    
    const handleEdit = (row) => {
      dialogTitle.value = '编辑流水'
      Object.assign(cashFlowForm, row)
      
      console.log('编辑行数据:', row)
      console.log('附件ID字符串:', row.fjIds)
      
      // 加载附件列表
      if (row.fjIds) {
        loadAttachments(row.fjIds)
      } else {
        console.log('没有附件ID，清空文件列表')
        fileList.value = []
      }
      
      cashFlowDialogVisible.value = true
    }
    
    // 重置流水表单
    const resetCashFlowForm = () => {
      Object.assign(cashFlowForm, {
        id: null,
        szrq: '',
        ywrq: '',
        szxmId: null,
        ywms: '',
        srje: null,
        zcje: null,
        yhzhId: null,
        htId: null,
        fpff: '',
        jfje: null,
        yfje: null,
        dfdwmc: '',
        jbr: '',
        bz: '',
        fjIds: ''
      })
      fileList.value = []
      
      // 清空验证状态
      validationStatus.value = { isValid: true, message: '' }
      amountValidationStatus.value = { isValid: true, message: '' }
    }
    
    // 验证收支日期
    const validateSzrq = async (yhzhId, szrq) => {
      try {
        if (!yhzhId || !szrq) {
          return { isValid: true, message: '缺少必要参数' }
        }
        
        const response = await cashFlowApi.validateSzrq(yhzhId, szrq)
        return response.data || response
      } catch (error) {
        console.error('验证收支日期失败:', error)
        // 如果验证接口不可用，默认通过
        return { isValid: true, message: '验证接口不可用，默认通过' }
      }
    }
    
    // 验证状态
    const validationStatus = ref({
      isValid: true,
      message: ''
    })
    
    // 金额验证状态
    const amountValidationStatus = ref({
      isValid: true,
      message: ''
    })
    
    // 防抖定时器
    let validationTimer = null
    
    // 实时验证收支日期（带防抖）
    const validateSzrqRealtime = async () => {
      // 清除之前的定时器
      if (validationTimer) {
        clearTimeout(validationTimer)
      }
      
      // 设置新的定时器，延迟500ms执行验证
      validationTimer = setTimeout(async () => {
        if (cashFlowForm.yhzhId && cashFlowForm.szrq) {
          try {
            const result = await validateSzrq(cashFlowForm.yhzhId, cashFlowForm.szrq)
            
            // 更新验证状态
            validationStatus.value = result
            
            if (!result.isValid) {
              ElMessage.warning(result.message || '收支日期不能早于银行账户启用日期')
            }
          } catch (error) {
            console.error('实时验证失败:', error)
            validationStatus.value = { isValid: true, message: '验证接口不可用' }
          }
        } else {
          validationStatus.value = { isValid: true, message: '' }
        }
      }, 500)
    }
    
    // 验证金额互斥
    const validateAmounts = () => {
      const srje = cashFlowForm.srje || 0
      const zcje = cashFlowForm.zcje || 0
      
      if (srje === 0 && zcje === 0) {
        amountValidationStatus.value = {
          isValid: false,
          message: '收入金额和支出金额不能同时为0'
        }
        ElMessage.warning('收入金额和支出金额不能同时为0')
        return false
      } else if (srje > 0 && zcje > 0) {
        amountValidationStatus.value = {
          isValid: false,
          message: '收入金额和支出金额不能同时大于0'
        }
        ElMessage.warning('收入金额和支出金额不能同时大于0')
        return false
      } else {
        amountValidationStatus.value = {
          isValid: true,
          message: '金额验证通过'
        }
        return true
      }
    }
    
    // 提交流水表单
    const submitCashFlow = async () => {
      try {
        await cashFlowFormRef.value.validate()
        submitLoading.value = true
        
        // 验证收支日期
        if (cashFlowForm.yhzhId && cashFlowForm.szrq) {
          const validationResult = await validateSzrq(cashFlowForm.yhzhId, cashFlowForm.szrq)
          
          if (!validationResult.isValid) {
            ElMessage.error(validationResult.message || '收支日期不能早于银行账户启用日期')
            return
          }
        }
        
        // 验证金额互斥
        if (!validateAmounts()) {
          return
        }
        
        // 处理附件ID
        const attachmentIds = fileList.value
          .filter(file => file.response && file.response.id)
          .map(file => file.response.id)
          .join(',')
        
        const submitData = {
          ...cashFlowForm,
          fjIds: attachmentIds
        }
        
        if (cashFlowForm.id) {
          // 编辑模式
          await cashFlowApi.update(cashFlowForm.id, submitData)
          ElMessage.success('编辑成功')
        } else {
          // 新建模式
          await cashFlowApi.create(submitData)
          ElMessage.success('新建成功')
        }
        
        cashFlowDialogVisible.value = false
        loadData()
      } catch (error) {
        console.error('提交失败:', error)
        ElMessage.error('提交失败')
      } finally {
        submitLoading.value = false
      }
    }
    
    // 文件上传相关方法
    const beforeFileUpload = (file) => {
      const isValidType = /\.(jpg|jpeg|png|gif|pdf|doc|docx|xls|xlsx)$/i.test(file.name)
      const isLt10M = file.size / 1024 / 1024 < 10
      
      if (!isValidType) {
        ElMessage.error('只能上传图片、PDF、Word、Excel文件!')
        return false
      }
      if (!isLt10M) {
        ElMessage.error('文件大小不能超过10MB!')
        return false
      }
      return true
    }
    
    const handleFileSuccess = (response, file, fileList) => {
      ElMessage.success('文件上传成功')
    }
    
    const handleFileError = (error, file, fileList) => {
      ElMessage.error('文件上传失败')
    }
    
    const handleFilePreview = (file) => {
      // 预览文件
      if (file.response && file.response.url) {
        window.open(file.response.url)
      }
    }
    
    const handleFileRemove = (file, fileList) => {
      ElMessage.success('文件已移除')
    }
    
    // 加载附件列表
    const loadAttachments = async (attachmentIds) => {
      if (!attachmentIds) return
      
      try {
        // 将字符串格式的附件ID转换为数组
        const ids = attachmentIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
        
        console.log('处理后的附件ID数组:', ids)
        
        if (ids.length === 0) {
          console.log('没有有效的附件ID')
          fileList.value = []
          return
        }
        
        const response = await attachmentApi.getAttachmentsBatch(ids)
        const attachments = response.data || response || []
        
        console.log('获取到的附件列表:', attachments)
        
        fileList.value = attachments.map(attachment => ({
          name: attachment.originalFilename || `附件_${attachment.id}`,
          url: attachment.url || `#`,
          uid: attachment.id,
          status: 'success',
          response: attachment
        }))
        
        console.log('处理后的文件列表:', fileList.value)
      } catch (error) {
        console.error('加载附件失败:', error)
        ElMessage.error('加载附件失败')
        fileList.value = []
      }
    }
    
    const handleDelete = async (row) => {
      try {
        await ElMessageBox.confirm('确定要删除这条流水记录吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await cashFlowApi.deleteById(row.id)
        ElMessage.success('删除成功')
        loadData()
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除失败:', error)
          ElMessage.error('删除失败')
        }
      }
    }
    
    const handleExport = async () => {
      try {
        // 安全检查
        if (!state) {
          console.error('state 未定义')
          ElMessage.error('导出失败：表格状态未初始化')
          return
        }
        
        const params = { ...searchParams }
        
        // 处理日期范围参数
        if (searchParams.dateRange && Array.isArray(searchParams.dateRange) && searchParams.dateRange.length === 2) {
          params.startDate = searchParams.dateRange[0]
          params.endDate = searchParams.dateRange[1]
          // 删除dateRange参数，避免传递给API
          delete params.dateRange
        }
        
        // 添加搜索关键词参数（安全检查）
        const searchKeyword = state?.value?.searchKeyword || ''
        const textFilter = textFilterValue.value || ''
        
        // 优先使用文本过滤，如果没有则使用搜索关键词
        if (textFilter) {
          params.search = textFilter
        } else if (searchKeyword) {
          params.search = searchKeyword
        }
        
        // 移除可能的undefined值
        Object.keys(params).forEach(key => {
          if (params[key] === undefined || params[key] === null) {
            delete params[key]
          }
        })
        
        console.log('handleExport 处理后的参数:', params)
        console.log('state:', state)
        console.log('state.value:', state?.value)
        console.log('searchKeyword:', searchKeyword)
        console.log('textFilterValue.value:', textFilterValue.value)
        console.log('cashFlowApi:', cashFlowApi)
        console.log('cashFlowApi.export:', cashFlowApi.export)
        
        // 显示加载状态
        ElMessage.info('正在导出Excel文件，请稍候...')
        
        // 检查导出函数是否存在
        if (!cashFlowApi.export) {
          throw new Error('导出功能未实现')
        }
        
        const response = await cashFlowApi.export(params)
        
        // 检查响应状态
        if (!response.data) {
          throw new Error('导出失败：服务器未返回数据')
        }
        
        // 检查响应类型
        const contentType = response.headers['content-type']
        if (!contentType || !contentType.includes('spreadsheetml.sheet')) {
          console.warn('响应Content-Type不是Excel格式:', contentType)
        }
        
        // 创建Blob对象
        const blob = new Blob([response.data], { 
          type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' 
        })
        
        // 检查Blob大小
        if (blob.size === 0) {
          throw new Error('导出失败：文件大小为0')
        }
        
        // 创建下载链接
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = `出纳流水_${new Date().toISOString().split('T')[0]}.xlsx`
        
        // 触发下载
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        
        // 清理URL对象
        window.URL.revokeObjectURL(url)
        
        ElMessage.success('导出成功')
      } catch (error) {
        console.error('导出失败:', error)
        
        // 更详细的错误信息
        let errorMessage = '导出失败'
        if (error.response) {
          // 服务器返回错误
          if (error.response.status === 404) {
            errorMessage = '导出接口不存在'
          } else if (error.response.status === 500) {
            errorMessage = '服务器内部错误'
          } else if (error.response.status === 401) {
            errorMessage = '未授权，请重新登录'
          } else {
            errorMessage = `导出失败 (${error.response.status})`
          }
        } else if (error.request) {
          // 网络错误
          errorMessage = '网络连接失败'
        } else {
          // 其他错误
          errorMessage = error.message || '导出失败'
        }
        
        ElMessage.error(errorMessage)
      }
    }
    
    const showAttachments = async (row) => {
      if (!row.fjIds) return
      
      selectedCashFlow.value = row
      
      try {
        const ids = row.fjIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id))
        if (ids.length === 0) {
          attachmentList.value = []
          attachmentDialogVisible.value = true
          return
        }
        
        const response = await attachmentApi.getAttachmentsBatch(ids)
        const data = response.data || response || []
        attachmentList.value = Array.isArray(data) ? data : []
        attachmentDialogVisible.value = true
      } catch (error) {
        console.error('加载附件失败:', error)
        ElMessage.error('加载附件失败')
      }
    }
    
    const previewAttachment = async (attachment) => {
      // 显示加载提示
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在加载预览...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      try {
        const response = await attachmentApi.previewAttachment(attachment.id)
        
        // 根据文件类型处理预览
        const fileType = attachment.fileType || 'application/octet-stream'
        const blob = new Blob([response.data], { type: fileType })
        const url = window.URL.createObjectURL(blob)
        
        // 对于PDF文件，直接在新窗口打开
        if (fileType === 'application/pdf' || attachment.originalFilename?.toLowerCase().endsWith('.pdf')) {
          window.open(url, '_blank')
        } else if (fileType.startsWith('image/')) {
          // 图片文件直接在新窗口打开
          window.open(url, '_blank')
        } else if (fileType.startsWith('text/')) {
          // 文本文件在新窗口打开
          window.open(url, '_blank')
        } else {
          // 其他文件类型，提示下载
          ElMessage.info('此文件类型不支持预览，请下载后查看')
          const link = document.createElement('a')
          link.href = url
          link.download = attachment.originalFilename || `附件_${attachment.id}`
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link)
        }
        
        // 清理URL对象
        setTimeout(() => window.URL.revokeObjectURL(url), 1000)
        ElMessage.success('预览已打开')
      } catch (error) {
        console.error('预览附件失败:', error)
        ElMessage.error('预览失败')
      } finally {
        loadingInstance.close()
      }
    }
    
    const downloadAttachment = async (attachment) => {
      // 显示加载提示
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在准备下载...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      try {
        const response = await attachmentApi.downloadAttachment(attachment.id)
        const blob = new Blob([response.data])
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = attachment.originalFilename
        link.click()
        window.URL.revokeObjectURL(url)
        ElMessage.success('下载成功')
      } catch (error) {
        console.error('下载附件失败:', error)
        ElMessage.error('下载附件失败')
      } finally {
        loadingInstance.close()
      }
    }
    
    const deleteAttachment = async (attachment) => {
      try {
        await ElMessageBox.confirm('确定要删除这个附件吗？', '确认删除', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        await attachmentApi.deleteAttachment(attachment.id)
        ElMessage.success('删除成功')
        // 从列表中移除
        const index = attachmentList.value.findIndex(item => item.id === attachment.id)
        if (index > -1) {
          attachmentList.value.splice(index, 1)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除附件失败:', error)
          ElMessage.error('删除附件失败')
        }
      }
    }
    
    // 工具方法
    const hasChildren = (data) => {
      // 检查是否有子节点，如果有子节点则禁用（只能选择叶子节点）
      return data.children && Array.isArray(data.children) && data.children.length > 0
    }
    
    // 格式化日期为 YYYY-MM-DD 格式，避免时区问题
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    const formatCurrency = (amount) => {
      if (!amount) return '0.00'
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(amount)
    }
    
    const formatNumber = (value) => {
      if (value === null || value === undefined) return '0.00'
      return new Intl.NumberFormat('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      }).format(value)
    }
    
    const formatFileSize = (bytes) => {
      if (!bytes) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    const formatAttachmentDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleDateString('zh-CN') + ' ' + date.toLocaleTimeString('zh-CN', { hour12: false })
    }
    
    // 初始化
    onMounted(async () => {
      try {
        // 保存原始列配置
        originalTableColumns.value = JSON.parse(JSON.stringify(tableColumns.value))
        
        // 加载保存的列配置
        const savedColumns = localStorage.getItem('cashFlowTableColumns')
        if (savedColumns) {
          const savedConfig = JSON.parse(savedColumns)
          tableColumns.value.forEach((column, index) => {
            const savedColumn = savedConfig.find(c => c.prop === column.prop)
            if (savedColumn) {
              column.visible = savedColumn.visible
              column.width = savedColumn.width
            }
          })
        }
        
        await Promise.all([
          loadBankAccounts(),
          loadIncomeExpenseTree(),
          searchContracts() // 初始加载合同列表
        ])
        
        // 检查是否需要显示银行账户选择对话框
        const savedBankAccountId = localStorage.getItem('cashFlowDefaultBankAccount')
        if (savedBankAccountId) {
          searchParams.yhzhId = parseInt(savedBankAccountId)
          updateSearchParams(searchParams)
        } else {
          // 如果没有保存的默认银行账户，显示选择对话框
          showBankAccountDialog.value = true
        }
        
        // 确保在初始化完成后加载数据
        await loadData()
      } catch (error) {
        console.error('初始化失败:', error)
      }
    })
</script>

<style scoped>
.page-container {
  padding: 20px;
  height: 100vh;
  width: 100%;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  overflow: hidden;
  max-width: 100%;
}



.bank-account-select,
.date-range-select {
  display: flex;
  align-items: center;
  gap: 8px;
}

.date-range-select {
  position: relative;
}

.date-picker-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-range-select .el-date-editor {
  border-radius: 6px;
  border: 1px solid #dcdfe6;
  transition: all 0.3s;
}

.date-range-select .el-date-editor:hover {
  border-color: var(--primary-color, #409eff);
}

.date-range-select .el-date-editor:focus-within {
  border-color: var(--primary-color, #409eff);
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.label {
  color: #409eff;
  font-weight: 500;
  white-space: nowrap;
}

.help-icon {
  color: #909399;
  font-size: 14px;
  margin-left: 4px;
  cursor: pointer;
}

.help-icon:hover {
  color: var(--primary-color, #409eff);
}

.quick-date-buttons {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
}

.quick-date-buttons .el-button {
  font-size: 11px;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 500;
  height: 28px;
  line-height: 1;
}

  .quick-date-buttons .el-button .el-icon {
  margin-right: 2px;
  font-size: 10px;
}

/* 日期选择器容器样式优化 */
.date-picker-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-picker-container .el-date-picker {
  flex: 1;
}

.date-picker-container .el-dropdown {
  flex-shrink: 0;
}

/* 快速选择下拉菜单样式 */
.date-picker-container .el-dropdown .el-button {
  height: 32px;
  padding: 0 12px;
  font-size: 12px;
  border-radius: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.date-picker-container .el-dropdown .el-button .el-icon {
  font-size: 12px;
}

.date-picker-container .el-dropdown .el-button .el-icon--right {
  margin-left: 4px;
}

/* 下拉菜单项样式 */
.date-picker-container .el-dropdown-menu .el-dropdown-item {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  font-size: 12px;
}

.date-picker-container .el-dropdown-menu .el-dropdown-item .el-icon {
  font-size: 12px;
  color: var(--primary-color, #409eff);
}
  
  /* 对话框样式 - 与主题协调 */
  .cash-flow-dialog {
    border-radius: 12px;
    overflow: hidden;
  }
  
  .cash-flow-dialog :deep(.el-dialog__header) {
    background: var(--primary-color, #409eff);
    color: white;
    padding: 20px;
    margin: 0;
  }
  
  .cash-flow-dialog :deep(.el-dialog__title) {
    color: white;
    font-weight: 600;
    font-size: 18px;
  }
  
  .cash-flow-dialog :deep(.el-dialog__body) {
    padding: 30px;
    background: rgba(255, 255, 255, 0.95);
  }
  
  .cash-flow-dialog :deep(.el-dialog__footer) {
    background: rgba(248, 250, 252, 0.95);
    padding: 20px 30px;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
  }
  
  /* 表单样式 */
  .cash-flow-form {
    max-height: 600px;
    overflow-y: auto;
  }
  
  .form-section {
    margin-bottom: 15px;
    padding: 15px;
    background: rgba(248, 250, 252, 0.5);
    border-radius: 8px;
    border: 1px solid rgba(0, 0, 0, 0.05);
  }
  
  .form-section:last-child {
    margin-bottom: 0;
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 600;
    color: var(--primary-color, #409eff);
    margin-bottom: 10px;
    padding-bottom: 8px;
    border-bottom: 2px solid var(--primary-color, #409eff);
  }
  
  .form-row {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 20px;
    margin-bottom: 5px;
  }
  
  .form-row:last-child {
    margin-bottom: 0;
  }
  
  /* 独占一行的表单项 */
  .form-row.single {
    grid-template-columns: 1fr;
  }
  
  /* 上传区域样式 */
  .upload-area {
    width: 100%;
  }
  
  .upload-area :deep(.el-upload--picture-card) {
    width: 100px;
    height: 100px;
    border: 2px dashed var(--primary-color, #409eff);
    border-radius: 8px;
    background: rgba(64, 158, 255, 0.05);
    transition: all 0.3s;
  }
  
  .upload-area :deep(.el-upload--picture-card:hover) {
    border-color: var(--primary-color, #409eff);
    background: rgba(64, 158, 255, 0.1);
  }
  
  .upload-text {
    color: var(--primary-color, #409eff);
    font-size: 12px;
    margin-top: 5px;
  }
  
  /* 统计结果样式 */
  .balance-results {
    margin-top: 20px;
  }
  
  .balance-results h4 {
    margin-bottom: 15px;
    color: var(--primary-color, #409eff);
    font-weight: 600;
  }
  
  .statistics-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 15px;
    margin-bottom: 15px;
  }
  
  .stat-item {
    background: rgba(248, 250, 252, 0.8);
    border: 1px solid rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    padding: 15px;
    text-align: center;
  }
  
  .stat-label {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
  }
  
  .stat-value {
    font-size: 18px;
    font-weight: 600;
  }
  
  .stat-value.income {
    color: #67c23a;
  }
  
  .stat-value.expense {
    color: #f56c6c;
  }
  
  .date-range {
    text-align: center;
    color: #999;
    font-size: 14px;
    margin-top: 10px;
  }
  
  /* 余额表格样式 */
  .balance-table {
    margin-top: 15px;
  }
  
  .balance-table :deep(.el-table__header) {
    background-color: var(--primary-color, #409eff);
  }
  
  .balance-table :deep(.el-table__header th) {
    background-color: var(--primary-color, #409eff);
    color: white;
    font-weight: 600;
  }
  
  .balance-table :deep(.el-table__body tr:hover) {
    background-color: rgba(64, 158, 255, 0.1);
  }
  
  .amount-text {
    font-weight: 600;
  }
  
  .income-amount {
    color: #67c23a;
    font-weight: 600;
  }
  
  .expense-amount {
    color: #f56c6c;
    font-weight: 600;
  }
  
  /* 验证提示样式 */
  .validation-tip {
    margin-top: 5px;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 5px;
  }
  
  .validation-tip .valid {
    color: #67c23a;
  }
  
  .validation-tip .invalid {
    color: #f56c6c;
  }
  
  /* 金额验证提示样式 */
  .amount-validation-tip {
    margin-top: 5px;
    font-size: 12px;
    display: flex;
    align-items: center;
    gap: 5px;
    padding: 5px 10px;
    background: rgba(248, 250, 252, 0.5);
    border-radius: 4px;
    border: 1px solid rgba(0, 0, 0, 0.05);
  }
  
  .amount-validation-tip .valid {
    color: #67c23a;
  }
  
  .amount-validation-tip .invalid {
    color: #f56c6c;
  }
  
  /* 其他对话框样式 */
  .balance-query-dialog,
  .internal-transfer-dialog,
  .attachment-dialog,
  .income-expense-dialog,
  .text-filter-dialog,
  .column-config-dialog,
  .contract-dialog,
  .bank-account-dialog {
    border-radius: 12px;
    overflow: hidden;
  }
  
  .balance-query-dialog :deep(.el-dialog__header),
  .internal-transfer-dialog :deep(.el-dialog__header),
  .attachment-dialog :deep(.el-dialog__header),
  .income-expense-dialog :deep(.el-dialog__header),
  .text-filter-dialog :deep(.el-dialog__header),
  .column-config-dialog :deep(.el-dialog__header),
  .contract-dialog :deep(.el-dialog__header),
  .bank-account-dialog :deep(.el-dialog__header) {
    background: var(--primary-color, #409eff);
    color: white;
    padding: 20px;
    margin: 0;
  }
  
  .balance-query-dialog :deep(.el-dialog__title),
  .internal-transfer-dialog :deep(.el-dialog__title),
  .attachment-dialog :deep(.el-dialog__title),
  .income-expense-dialog :deep(.el-dialog__title),
  .text-filter-dialog :deep(.el-dialog__title),
  .column-config-dialog :deep(.el-dialog__title),
  .contract-dialog :deep(.el-dialog__title),
  .bank-account-dialog :deep(.el-dialog__title) {
    color: white;
    font-weight: 600;
    font-size: 18px;
  }
  
  .balance-query-dialog :deep(.el-dialog__body),
  .internal-transfer-dialog :deep(.el-dialog__body),
  .attachment-dialog :deep(.el-dialog__body),
  .income-expense-dialog :deep(.el-dialog__body),
  .text-filter-dialog :deep(.el-dialog__body),
  .column-config-dialog :deep(.el-dialog__body),
  .contract-dialog :deep(.el-dialog__body),
  .bank-account-dialog :deep(.el-dialog__body) {
    padding: 30px;
    background: rgba(255, 255, 255, 0.95);
  }
  
  .balance-query-dialog :deep(.el-dialog__footer),
  .internal-transfer-dialog :deep(.el-dialog__footer),
  .attachment-dialog :deep(.el-dialog__footer),
  .income-expense-dialog :deep(.el-dialog__footer),
  .text-filter-dialog :deep(.el-dialog__footer),
  .column-config-dialog :deep(.el-dialog__footer),
  .contract-dialog :deep(.el-dialog__footer),
  .bank-account-dialog :deep(.el-dialog__footer) {
    background: rgba(248, 250, 252, 0.95);
    padding: 20px 30px;
    border-top: 1px solid rgba(0, 0, 0, 0.1);
  }

.main-actions {
  display: flex;
  gap: 10px;
  margin-left: auto;
}

.advanced-filter {
  background: #f5f7fa;
  padding: 15px 20px;
  border-radius: 8px;
  margin-bottom: 15px;
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.income-expense-dialog,
.text-filter-dialog {
  padding: 20px 0;
}

.filter-tips {
  margin-top: 10px;
  color: #909399;
  font-size: 12px;
}

.filter-tips p {
  margin: 0;
}

.dialog-tip {
  margin-bottom: 15px;
  color: #666;
  font-size: 14px;
  line-height: 1.5;
}

  .table-container {
    flex: 1;
    width: 100%;
    min-height: 0;
    max-width: 100%;
    background: white;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    border: 1px solid rgba(0, 0, 0, 0.05);
    padding: 20px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    box-sizing: border-box;
  }

  .table-container .base-table-container {
    flex: 1;
    width: 100%;
    min-height: 0;
    max-width: 100%;
    display: flex;
    flex-direction: column;
    box-sizing: border-box;
  }
  
  /* 表格样式与主题协调 */
  .table-container :deep(.el-table) {
    border-radius: 8px;
    overflow: hidden;
  }
  
  .table-container :deep(.el-table__header) {
    background: var(--primary-color, #409eff);
  }
  
  .table-container :deep(.el-table__header th) {
    background: var(--primary-color, #409eff) !important;
    color: white !important;
    font-weight: 600;
  }
  
  .table-container :deep(.el-table__body tr:hover) {
    background-color: rgba(64, 158, 255, 0.1);
  }
  
  /* 按钮样式与主题协调 */
  .header-actions .el-button {
    border-radius: 6px;
    font-weight: 500;
  }
  
  .header-actions .el-button--primary {
    background: var(--primary-color, #409eff);
    border-color: var(--primary-color, #409eff);
  }
  
  .header-actions .el-button--primary:hover {
    background: var(--primary-color-hover, #66b1ff);
    border-color: var(--primary-color-hover, #66b1ff);
  }
  
  /* 响应式设计 */
  @media (max-width: 1920px) {
    .page-container {
      padding: 15px;
    }
    
    .header-actions {
      gap: 15px;
    }
  }
  
  @media (max-width: 1440px) {
    .page-container {
      padding: 10px;
    }
    
    .header-actions {
      gap: 10px;
    }
    
    .bank-account-select .el-select {
      width: 180px !important;
    }
    
    .date-range-select .el-date-picker {
      width: 320px !important;
    }
    
    .quick-date-buttons {
      gap: 6px;
    }
    
    .quick-date-buttons .el-button {
      font-size: 11px;
      padding: 3px 6px;
    }
  }
  
  @media (max-width: 1200px) {
    .header-actions {
      flex-direction: column;
      align-items: stretch;
      gap: 10px;
    }
    
    .main-actions {
      margin-left: 0;
      justify-content: center;
    }
  }

.pagination-wrapper {
  padding: 15px;
  background: white;
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #eee;
  flex-shrink: 0;
  margin-top: auto;
}

/* 列配置样式已删除 */

.balance-query {
  max-height: 400px;
  overflow-y: auto;
}

/* 附件对话框样式 */
.attachment-dialog .el-dialog__body {
  padding: 0;
}

.attachment-content {
  padding: 20px;
}

.cashflow-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
  border-left: 4px solid #409eff;
}

.cashflow-info h4 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.cashflow-info p {
  margin: 5px 0;
  color: #606266;
  font-size: 14px;
}

.attachment-list {
  max-height: 400px;
  overflow-y: auto;
}

.attachment-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  margin-bottom: 10px;
  background: white;
  transition: all 0.3s ease;
}

.attachment-item:hover {
  border-color: #409eff;
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
}

.attachment-info {
  flex: 1;
  margin-right: 15px;
}

.attachment-name {
  font-weight: 500;
  color: #303133;
  font-size: 14px;
  margin-bottom: 8px;
  word-break: break-all;
}

.attachment-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  font-size: 12px;
  color: #909399;
}

.file-size,
.file-type,
.upload-time,
.sub-directory {
  display: flex;
  align-items: center;
  gap: 4px;
}

.attachment-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

.no-attachments {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
}

.income-amount {
  color: #67c23a;
  font-weight: 500;
}

.expense-amount {
  color: #f56c6c;
  font-weight: 500;
}

.danger-text {
  color: #f56c6c;
}

.danger-text:hover {
  color: #f78989;
}

/* 列配置样式 */
.column-config {
  max-height: 500px;
  overflow-y: auto;
}

.column-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.column-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  background: #fafafa;
}

.column-info {
  flex: 1;
}

.column-width {
  display: flex;
  align-items: center;
  gap: 8px;
}

.width-label {
  font-size: 12px;
  color: #606266;
}

.unit {
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 